package cn.pangza.redis.init;

import cn.pangza.redis.utils.SpringContextUtil;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

// 项目启动时工作一些事情
@Component
public class InitCache implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        // 知道那些缓存需要预热
        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        Map<String, AbstractCache> beansOfType = applicationContext.getBeansOfType(AbstractCache.class);
        // 调用 init 方法
        if(beansOfType.isEmpty()) {
            return;
        }
        for (Map.Entry<String, AbstractCache> entry: beansOfType.entrySet()) {
            AbstractCache bean = (AbstractCache) SpringContextUtil.getBean(entry.getValue().getClass());
            bean.initCache();
        }
    }
}
